<?php
include_once $_SERVER["DOCUMENT_ROOT"].'/service/entite/Entite.php';
include_once $_SERVER["DOCUMENT_ROOT"].'/outils/database/Database.php';
include_once $_SERVER["DOCUMENT_ROOT"].'/outils/exceptions/DAOException.php';

class NewsDAO {
	
	private function NewsDAO() {
		//évite la construction
	}
		
	public static function getListeNews() {
		$database = Database::getInstance();
		$result = $database->executeQueryAndClose("SELECT id, dateheure,titre,description FROM news ORDER BY dateheure DESC");
		$newsArray = Array();
		foreach ($result as $row) {
			$newsArray[] = NewsDAO::getNewsFromDatabaseRow($row);
		}
		return $newsArray;
	}
	
	public static function getNewsByID($id) {
		
		$result = Database::getInstance()->executeQueryAndClose("SELECT id, dateheure,titre,description FROM news WHERE id =$id");
		foreach ($result as $row){
			return NewsDAO::getNewsFromDatabaseRow($row);
		}
		throw new MissingDataException("Impossible de trouver la news avec l'ID ${id}");
	}
	
	public static function save(NewsEntite $newsEntite) {
		if($newsEntite->id == Entite::getUnpersistedId()) {
			$result = NewsDAO::insert($newsEntite);
		} else {
			$result = NewsDAO::update($newsEntite);
			if ($result != 1) {
				$titre = $newsEntite->titre;
				throw new DAOException("La sauvegarde de l'entite $titre a mis à jour $result lignes");
			}
		}
	}
	
	public static function delete($id) {
		
		$result = Database::getInstance()->executeUpdateQueryAndClose("DELETE FROM news WHERE id = $id") ;
		return $result;
	}
	
	private static function insert(NewsEntite $newsEntite) {
		
		$titre = mysql_escape_string($newsEntite->titre);
		$description = mysql_escape_string($newsEntite->description);
		$result = Database::getInstance()->executeInsertQuery("INSERT INTO news (dateheure,titre,description) values (NOW(),'$titre','$description')") ;
		return $result;
	}
	
	private static function update(NewsEntite $newsEntite) {
		
		$titre = mysql_escape_string($newsEntite->titre);
		$description = mysql_escape_string($newsEntite->description);
		$result = Database::getInstance()->executeUpdateQueryAndClose("UPDATE news SET dateheure = '$newsEntite->dateheure',titre = '$titre', description = '$description' WHERE id = $newsEntite->id");
		return $result;
	}
	
	private static function getNewsFromDatabaseRow($row) {
		$newsEntite = new NewsEntite();
		$newsEntite->id = $row['id'];
		$newsEntite->dateheure = $row['dateheure'];
		$newsEntite->titre = $row['titre'];
		$newsEntite->description = $row['description'];
		return $newsEntite;
	}
}
?>